package com.zyg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.dao.UserExMapper;
import com.zyg.pojo.UserEx;
import com.zyg.pojo.UserRole;
import com.zyg.service.UserExService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userExService")
public class UserExServiceImpl extends ServiceImpl<UserExMapper, UserEx> implements UserExService {

    @Autowired
    private UserExMapper userMapper;

    @Autowired
    private UserRoleServiceImpl userRoleService;

    // 此方法重写了父类的save方法
    @Override
    @Transactional
    public boolean save(UserEx user) {
        // 先新增用户
        int result = userMapper.insert(user);
        // 获取新增用户的主键
        int userId = user.getId();

        // 往user_role 插入数据
        Integer[] roleIds = user.getRoleIds();
        List<UserRole> userRoleList = new ArrayList<>();
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUId(userId);
                userRole.setRId(roleId);
                userRoleList.add(userRole);
            }
            userRoleService.saveBatch(userRoleList);
        }
        return result>0;
    }

    @Override
    public boolean updateById(UserEx user) {

        // 先更新用户
        int result = userMapper.updateById(user);
        // 删除用户对应的角色
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("u_id",user.getId());
        userRoleService.remove(queryWrapper);

        // 新增用户角色
        // 往user_role 插入数据
        Integer[] roleIds = user.getRoleIds();
        List<UserRole> userRoleList = new ArrayList<>();
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                UserRole userRole = new UserRole();
                userRole.setUId(user.getId());
                userRole.setRId(roleId);
                userRoleList.add(userRole);
            }
            userRoleService.saveBatch(userRoleList);
        }
        return result > 0;
    }
}